<?php
namespace Components\Traits;

trait ControllerBaseTraits {
	protected function returnByJson($data) {
		if(isset($_SERVER['HTTP_ORIGIN']) || $_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
			$this -> response
				-> setHeader('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN'])
				-> setHeader('Access-Control-Allow-Methods', 'GET, HEAD, POST, PUT, PATCH, DELETE')
				-> setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
				-> setHeader('Access-Control-Allow-Credentials', 'true');
		}

		return $this -> response
			-> setStatusCode(200, 'OK') -> sendHeaders()
			-> setContentType('application/json', 'UTF-8')
			-> setJsonContent($data);
	}

	protected function returnSuccessByJson($data) {
		return $this -> returnByJson(array_merge(['code' => 0], $data));
	}

	protected function returnFailByJson($data) {
		return $this -> returnByJson(array_merge(['code' => -1], $data));
	}
}
